﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
using System.Diagnostics;
using AOP.Attribute;
using AOP.Util;

namespace AOP.Interceptor
{
    public class ElapseInterceptor : IInterceptor
    {
        //建议配置在配置文件中
        private const bool IS_ELAPSELOG = true;

        public void Intercept(IInvocation invocation)
        {
            if (!RecordLogAndProcess(invocation))
            {
                invocation.Proceed();
            }
        }

        private bool RecordLogAndProcess(IInvocation invocation)
        {
            var result = false;
            if (IS_ELAPSELOG)
            {
                var attributes = invocation.Method.DeclaringType.GetCustomAttributes(typeof(AopLogoAttribute), false);
                if (attributes == null || !attributes.Any())
                {
                    attributes = invocation.Method.GetCustomAttributes(typeof(AopLogoAttribute), false);
                }
                if (attributes != null && attributes.Count() == 1)
                {
                    var attrbute = attributes.First() as AopLogoAttribute;
                    if (attrbute != null)
                    {
                        Stopwatch _stopwatch = new Stopwatch();
                        _stopwatch.Restart();
                        invocation.Proceed();
                        _stopwatch.Stop();
                        Log.Record(string.Format("{0}/{1}/{2}/{3}",
                            string.IsNullOrEmpty(attrbute.Topic) ? string.Empty : string.Concat("/", attrbute.Topic),
                            invocation.TargetType.FullName,
                            invocation.Method.Name,
                            attrbute.Step ?? string.Empty), _stopwatch.ElapsedMilliseconds);
                        result = true;
                    }
                }
            }
            return result;
        }
    }
}
